package com.tengju.support.application.message;

import com.tengju.support.domain.model.message.*;
import com.tengju.support.domain.model.user.UserId;
import com.tengju.support.domain.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("appPushSendStrategy")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class AppPushSendStrategy implements MessageSendStrategy {

    private final NotificationService notificationService;
    private final MessageRepository messageBatchRelationRepository;

    @Override
    public boolean send(MessageTask messageContent, List<Message> messageBatchRelationList) {

        Map<BatchId, List<Message>> messageBatchRelationMap = messageBatchRelationList.stream()
                .collect(Collectors.groupingBy(Message::getBatchId));

        boolean result = true;

        for (BatchId batchId : messageBatchRelationMap.keySet()) {
            try {
                List<Message> messageBatchRelations = messageBatchRelationMap.get(batchId);
                List<UserId> receiveUserIdList = messageBatchRelations.stream()
                        .map(Message::getUserId).collect(Collectors.toList());
                //发起推送
                boolean pushResult = notificationService.batchPush(batchId, messageContent.getTitle(),
                        messageContent.getContent(), receiveUserIdList);
                if (pushResult) {
                    //变更该批次发送状态
                    messageBatchRelationRepository.batchUpdateSendStatusByBatchId(batchId, SendStatus.SEND);
                } else {
                    result = false;
                }
            } catch (Exception e) {
                log.error("app推送失败,batchId:{}",batchId,e);
                result = false;
            }
        }

        return result;

    }
}
